package cn.stu.common.utils;


import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.*;
import lombok.extern.log4j.Log4j2;


/**
 * jwt
 *
 * @author 郑志豪
 * @date 2023/09/14
 */

@Log4j2
public class JwtHelper {

    private static final long TOKEN_EXPIRATION = 365L * 24 * 60 * 60 * 1000;
    /**
     * 令牌签名密钥
     */
    private static final String TOKEN_SIGN_KEY = "123456";

    /**
     * 创建令牌
     *
     * @param userId    用户标识
     * @param sessionId 会话标识
     * @return {@link String}
     */
    public static String createToken(Long userId, String sessionId) {
        return Jwts.builder()
                //分类
                .setSubject("AUTH-USER")
                //设置token有效时长
//                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //设置主体部分
                .claim("userId", userId)
                .claim("sessionId", sessionId)
                //签名部分
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 获取用户标识
     *
     * @param token 令 牌
     * @return {@link Long}
     */
    public static Long getUserId(String token) {
        try {
            if (StrUtil.isBlank(token)) {
                return null;
            }
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取会话 ID
     *
     * @param token 令 牌
     * @return {@link String}
     */
    public static String getSessionId(String token) {
        try {
            if (StrUtil.isBlank(token)) {
                return StrUtil.EMPTY;
            }
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("sessionId");
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, " ");
        System.out.println(token);
        Long userId = JwtHelper.getUserId(token);
        String username = JwtHelper.getSessionId(token);
        System.out.println(userId);
        System.out.println(username);
    }
}
